package aperturescience.resources;

import java.io.IOException;

import org.json.JSONException;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;

import aperturescience.types.Action;
import aperturescience.types.JSONMessageResponse;
import aperturescience.wargames.WarGamesApplication;

public class ActionsResource extends ServerResource{

	@Put("JSON")
	public JsonRepresentation putAction(Representation entity) {
		return postAction(entity);
	}
	
	@Post("JSON")
	public JsonRepresentation postAction(Representation entity) //throws IOException
	{
		JsonRepresentation result = null;
		try {
			Action action = new Action(entity);
			DatabaseResource db = new DatabaseResource(WarGamesApplication.couchdburl, WarGamesApplication.databasename);
			String actionId = db.createAction(action);
			if( actionId != null ) {
				result = JSONMessageResponse.generateMessageRep( 201, actionId );
			} else { // Patient is already registered.
				result = JSONMessageResponse.generateMessageRep( 409, "Conflict" );
			}
		}
		catch (IOException e) {
			result = JSONMessageResponse.generateMessageRep("999", e.toString());
			//TODO fix verbose error messages (above and below)
		}
		catch (JSONException e) {
			result = JSONMessageResponse.generateMessageRep("999", e.toString());
		}
		catch (Throwable e) {
			result = JSONMessageResponse.generateMessageRep("999", e.toString());
		}
		return result;
	}
	
	@Get("JSON")
	public JsonRepresentation toJSON() {
		DatabaseResource db = new DatabaseResource(WarGamesApplication.couchdburl, WarGamesApplication.databasename);
		return new JsonRepresentation(db.getAllActions());
	}
}
